<?php
/**
 * 2016/10/22 10:00:10
 * 张树超
 * 用户登录/注册
 */
namespace Home\Controller;

use Think\Controller;

class LoginController extends HomeController
{
	public function __construct() {
		parent::__construct();
	}

	/**
	 * @describe send verification code to user's mobile when user register
	 * @author Creatint
	 * @param $mobile user's mobile
	 */
	public function send_verification_code($mobile){
		//initiallize verification
		$verification_code = 0;
		if(!empty(session('verification_code')) && (time()-session("verification_time"))<10*60){
			$verification_code = session('verification_code');// erification code is not empty and time is in 10 minutes
		}else{
			$verification_code = rand(1000,9999);
			session('verification_code',$verification_code);
            // initialize time
			session("verification_time",time());//this time can't refresh
		}
        //refresh sending time 
		if( (time()-session("verification_time"))>60){
			session("verification_time",time());
		}

        //send erification code message to user's mobile
		$res = hook("send_verification_code",array('mobile'=>$mobile,'code'=>$verification_code));

		if($res){
			//success
			//record user's mobile
			session("verification_mobile",$mobile);
			$this->ajaxReturn(array('status'=>1,'time'=>session("verification_time")));
		}else{
			//failed
			$this->ajaxReturn(array('status'=>0,'time'=>session("verification_time"), 'msg'=>"发送失败"));
		}
 
	}
	public function check_verification_code($mobile,$code){
        if(!$mobile || !$code){
            $this->ajaxReturn(array('status'=>0,'msg'=>'验证码错误'));
        }
        $res = hook('check_verification_code',array('mobile'=>$mobile,'code'=>$code));
        
		if($res){
			$this->ajaxReturn(array('status'=>1,'msg'=>'验证码正确'));
		}else{
			$this->ajaxReturn(array('status'=>0,'msg'=>'验证码错误'));
		}
	}


	/**
	 * 用户登录/注册
	 */
    public function index() {
		if(!empty($_SESSION['member'])) { // 判断是否登录
			header('Location:'.U('Center/index')); // 跳转到个人中心
		}

		$this->assign("verification_time",session("verification_time"));
		if(IS_POST) {
			$act = I('post.act','','strip_tags');
			if($act == 'login') { // 登录 
				$acturl = I('acturl',U('Center/index'),'strip_tags'); // 成功跳转页面
				$User = D('User');
				if (!$User->create($_POST,4)){
					$this->errorAlert($User->getError()); // 验证提示
				} else {
					$msg = $User->login();
					if(empty($msg)) {
						$this->errorAlert('登录失败！');
					} else {
						$remember = I('post.remember','','intval');
						if($remember == 1) { // 记住密码
							$time = 60*60*24*30;
							setcookie('username',strip_tags($_POST['username']),time()+$time);// 记住用户名
							setcookie('password',strip_tags($_POST['password']),time()+$time);// 记住密码
						}
						$_SESSION['member'] = $msg;
						$this->successAlert('登录成功！',$acturl,true);
					}
				}

			}

			if($act == 'register') { // 注册
				if( empty(session('verification_code')) || session('verification_code') != $_POST['code']){
					//$this->errorAlert('验证码错误！');
				}
				if( session("verification_mobile") !=$_POST['mobile']){
					//$this->errorAlert('更换手机后需请重新验证！');
				}
				$acturl = I('post.acturl',U('Center/index'),'strip_tags'); // 成功跳转页面
				$User = D('Home/user');
				if(!$_POST['email']) unset($_POST['email']);
				if (!$User->create($_POST,1)){
					$this->errorAlert($User->getError()); // 验证提示
				} else {
					$msg = $User->register();
					if(empty($msg)) {
						$this->errorAlert('注册失败！'.$msg['msg']);
					} else {
						$info = $User->find($msg);
						$_SESSION['member'] = $info;
						$this->successAlert('注册成功！',$acturl);
					}
				}
				die();
			}
		}

		$type = I('get.type','login','strip_tags'); // login 登录 register 注册
		$this->assign('type',$type);
		
		$url = U('Center/index');
		$acturl = I('acturl',$url,'strip_tags'); // 登录、注册成功之后的跳转页面
		$this->assign('acturl',$acturl);

		$this->display();
    }

	/**
	 * 忘记密码
	 */
	public function forget() {
		$this->display();
	}

	/**
	 * 用户退出
	 */
	public function out() {
//		unset($_SESSION['member']);
        session("member",null);
        session_unset();
		$url = U('Index/index');
		$this->assign('info',array('msg'=>'退出成功！','url'=>$url));
		$this->display('Notice/location');
	}

	/**
	 * 成功跳转
	 */
	public function errorAlert($msg,$url) {
		$this->assign('info',array('msg'=>$msg,'url'=>$url));
		$this->display('Notice/login_error');
		die();
	}

	public function successAlert($msg,$url,$encode=false) {
		if($encode == true) {
			$url = urldecode($url);
		}
		$this->assign('info',array('msg'=>$msg,'url'=>$url));
		$this->display('Notice/login_success');
		die();
	}

	public function buy() {
		//C('URL_MODEL',2);
		Vendor('WxpayAPI.WxPayJsApiPay');	
		Vendor('WxpayAPI.log');	
		//初始化日志
		$logHandler= new \CLogFileHandler("logs/".date('Y-m-d').'.log');
		$log = \Log::Init($logHandler, 15);

		//打印输出数组信息
		/*
		function printf_info($data)
		{
			foreach($data as $key=>$value){
				echo "<font color='#00ff55;'>$key</font> : $value <br/>";
			}
		}
		 */
		//①、获取用户openid
		$tools = new \JsApiPay();
		$openId = $tools->GetOpenid();

		//②、统一下单
		$input = new \WxPayUnifiedOrder();
		$input->SetBody("腾讯充值中心-QQ会员充值"); //商品描述
		$input->SetAttach("1"); // 附加数据
		$input->SetOut_trade_no(\WxPayConfig::MCHID.date("YmdHis"));
		$input->SetTotal_fee("1"); // 金额
		$input->SetTime_start(date("YmdHis")); // 交易起始时间
		$input->SetTime_expire(date("YmdHis", time() + 600)); // 交易结束时间
		$input->SetGoods_tag("test"); // 商品标记
		$input->SetNotify_url("http://yshop.huiyouzan.com/index.php/Login/notify"); // 通知地址
		$input->SetTrade_type("JSAPI");
		$input->SetOpenid($openId); // 用户openid
		$order = \WxPayApi::unifiedOrder($input);
		//echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
		//printf_info($order);
		$jsApiParameters = $tools->GetJsApiParameters($order);
		//获取共享收货地址js函数参数
		//$editAddress = $tools->GetEditAddressParameters();
echo '
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/> 
    <title>微信支付样例-支付</title>
    <script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			"getBrandWCPayRequest",
			'.$jsApiParameters.',
			function(res){
				WeixinJSBridge.log(res.err_msg);
				alert(res.err_code+res.err_desc+res.err_msg);
			}
		);
	}

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener("WeixinJSBridgeReady", jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent("WeixinJSBridgeReady", jsApiCall); 
		        document.attachEvent("onWeixinJSBridgeReady", jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	</script>
	<link href="https://res.wx.qq.com/open/libs/weui/1.0.2/weui.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
	<div class="weui-form-preview">
		<div class="weui-form-preview__hd">
			<label class="weui-form-preview__label">付款金额</label>
			<em class="weui-form-preview__value">¥0.01</em>
		</div>
		<div class="weui-form-preview__bd">
			<p>
				<label class="weui-form-preview__label">商品</label>
				<span class="weui-form-preview__value">电动打蛋机</span>
			</p>
			<p>
				<label class="weui-form-preview__label">标题标题</label>
				<span class="weui-form-preview__value">名字名字名字</span>
			</p>
			<p>
				<label class="weui-form-preview__label">标题标题</label>
				<span class="weui-form-preview__value">很长很长的名字很长很长的名字很长很长的名字很长很长的名字很长很长的名字</span>
			</p>
		</div>
		<div class="weui-form-preview__ft">
			<a class="weui-form-preview__btn weui-form-preview__btn_primary" href="javascript:" onclick="callpay()">立即支付</a>
		</div>
	</div>
	-->
</body>
</html>
';
	}

	public function notify() {
		//echo file_get_contents('logs/txt.txt');
		Vendor('WxpayAPI.notify');	
		\Log::DEBUG("begin notify");
		$notify = new \PayNotifyCallBack();
		$notify->Handle(false);
	}

	public function weui() {
		echo '<html>
		<link href="https://res.wx.qq.com/open/libs/weui/1.0.2/weui.min.css" rel="stylesheet" type="text/css" />
		<body>
			<div class="weui-form-preview">
				<div class="weui-form-preview__hd">
					<label class="weui-form-preview__label">付款金额</label>
					<em class="weui-form-preview__value">¥2400.00</em>
				</div>
				<div class="weui-form-preview__bd">
					<p>
						<label class="weui-form-preview__label">商品</label>
						<span class="weui-form-preview__value">电动打蛋机</span>
					</p>
					<p>
						<label class="weui-form-preview__label">标题标题</label>
						<span class="weui-form-preview__value">名字名字名字</span>
					</p>
					<p>
						<label class="weui-form-preview__label">标题标题</label>
						<span class="weui-form-preview__value">很长很长的名字很长很长的名字很长很长的名字很长很长的名字很长很长的名字</span>
					</p>
				</div>
				<div class="weui-form-preview__ft">
					<a class="weui-form-preview__btn weui-form-preview__btn_primary" href="javascript:">操作</a>
				</div>
			</div>
		</body>
			</html>';
	}

}
